package wiki;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.LoginChecks;

/**
 * Servlet implementation class VerifyLogin
 */
@WebServlet("/VerifyLogin")
public class VerifyLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public VerifyLogin() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();

		String loginstatus = "failed";

		try {
			String username = request.getParameter("username");
			String password = request.getParameter("password");

			LoginChecks checklogindetail = new LoginChecks();

			boolean logintest = checklogindetail.loginvalidation(username,
					password);
				
			//logintest=true;
			
			if (logintest == true) {
				
				checklogindetail.setuser(username);
				HttpSession session = request.getSession(true);
		        session.setAttribute("isActive", true);
				session.setAttribute("username", username);
				//System.out.println("Login credentials valid");
				String userrole = checklogindetail
						.accessrightsvalidation(username);
				String[] uname = username.split("\\.");
				String ufname = uname[0];
				String ulname = uname[1];

				ufname = ufname.substring(0, 1).toUpperCase()
						+ ufname.substring(1);
				ulname = ulname.substring(0, 1).toUpperCase()
						+ ulname.substring(1);

				String user = ufname + ulname;
				session.setAttribute("firstname", ufname);
				session.setAttribute("userrole", userrole);
				session.setAttribute("user", user);
				loginstatus = "success";
				
//				session.setAttribute("firstname", "Mona");
//				session.setAttribute("userrole", "0");
//				session.setAttribute("user", "Mona Chandrapal");
//				loginstatus = "success";
				
			} else {
				loginstatus = "failed";
			}

		} catch (Exception e) {
			System.out
					.println("Exception when verifying login " + e.toString());
		}

		
		out.println("{\"loginstatus\": [{\"status\": \"" + loginstatus
				+ "\"}]}");

	}

}
